package com.example.j202411.views.Fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.j202411.adapter.ChatAdapter;
import com.example.j202411.databinding.FragmentChatBinding;
import com.example.j202411.Model.ChatMessage;
import com.example.j202411.viewmodel.ChatViewModel;

import java.util.ArrayList;
import java.util.List;

public class ChatFragment extends Fragment {

    private FragmentChatBinding binding;
    private ChatViewModel viewModel;
    private ChatAdapter chatAdapter;
    private List<ChatMessage> chatMessages = new ArrayList<>();
    private boolean isFirstMessage = true;
    private int messageCount = 0;
    private static final int AUTO_SCROLL_THRESHOLD = 5; // 自动滚动的阈值

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentChatBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        viewModel = new ViewModelProvider(requireActivity()).get(ChatViewModel.class);

        setupRecyclerView();
        setupObservers();
        setupListeners();
    }

    private void setupRecyclerView() {
        chatAdapter = new ChatAdapter(chatMessages);
        binding.rvChatMessages.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.rvChatMessages.setAdapter(chatAdapter);
    }

    private void setupObservers() {
        viewModel.getChatResponse().observe(getViewLifecycleOwner(), response -> {
            if (response.getCode() == 200) {
                int lastPosition = chatMessages.size() - 1;
                if (lastPosition >= 0 && chatMessages.get(lastPosition).isAiMessage() && chatMessages.get(lastPosition).isLoading()) {
                    chatAdapter.updateMessage(lastPosition, response.getAnswer());
                } else {
                    chatAdapter.addMessage(new ChatMessage(response.getAnswer(), ChatMessage.TYPE_AI));
                }
                messageCount++;
                scrollToEndIfNeeded();
                binding.rvChatMessages.scrollToPosition(chatMessages.size() - 1);
            } else {
                // Show error
            }
        });
    }

    private void setupListeners() {
        binding.btnSend.setOnClickListener(v -> {
            String message = binding.etMessage.getText().toString();
            if (!message.isEmpty()) {
                if (isFirstMessage) {
                    isFirstMessage = false;
                    updatePlaceholderVisibility();
                }
                chatAdapter.addMessage(new ChatMessage(message, ChatMessage.TYPE_USER));
                messageCount++;
                scrollToEndIfNeeded();
                viewModel.sendMessage(message);
                chatAdapter.addMessage(new ChatMessage("", ChatMessage.TYPE_AI, true)); // 添加带有加载动画的 AI 消息
                binding.etMessage.setText("");
            }
        });

        binding.btnNewChat.setOnClickListener(v -> {
            // 清空聊天记录
            chatMessages.clear();
            chatAdapter.notifyDataSetChanged();
            messageCount = 0;
            isFirstMessage = true;
            updatePlaceholderVisibility();
        });
    }

    private void updatePlaceholderVisibility() {
        if (isFirstMessage) {
            binding.tvPlaceholder.setVisibility(View.VISIBLE);
            binding.rvChatMessages.setVisibility(View.GONE);
        } else {
            binding.tvPlaceholder.setVisibility(View.GONE);
            binding.rvChatMessages.setVisibility(View.VISIBLE);
        }
    }

    private void scrollToEndIfNeeded() {
        if (messageCount >= AUTO_SCROLL_THRESHOLD) {
            binding.rvChatMessages.post(() -> {
                LinearLayoutManager layoutManager = (LinearLayoutManager) binding.rvChatMessages.getLayoutManager();
                if (layoutManager != null) {
                    layoutManager.scrollToPosition(chatMessages.size() - 1);
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}